package com.example.doctor.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Dto;
import com.example.common.DtoUtil;
import com.example.doctor.service.CommentService;
import com.example.pojo.FreeQuestion;
import com.example.pojo.GdComment;
import com.example.pojo.GdUser;
import com.example.utils.ErrorCode;
import com.example.vo.AskQusetionVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by LENOVO on 2018/9/23.
 */
@RestController
@RequestMapping("/api")
public class CommentController {

    @Resource
    private CommentService commentService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 医生评论
     * @return
     */
    @ApiOperation(value="获取医生评论列表",httpMethod = "GET", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="获取医生评论列表")
    @RequestMapping(value = "/getCommentList/{doctorId}", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Dto getCommentList(@PathVariable String doctorId, HttpServletResponse response)
    {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<GdComment> commentList=null;
        try {
            commentList=commentService.getCommentList(doctorId);
        }
        catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取医生评论列表失败！", ErrorCode.SEARCH_abnormal_FAILED);
        }
        if(commentList !=null)
        {
            return DtoUtil.returnSuccess("获取医生评论列表成功!",commentList);
        }
        else
        {
            return DtoUtil.returnSuccess("没有医生评论数据，请重新查询",commentList);
        }
    }


    /**
     * 图片上传
     * @return
     */
    @ApiOperation(value="图片上传",httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class,notes="图片上传")
    @RequestMapping(value = "/uploadPic", produces = "application/json", method = RequestMethod.POST)
    @ResponseBody
    public Dto uploadPic(HttpServletResponse response, HttpServletRequest request)
    {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Dto<Object> dto = new Dto<Object>();
        List<String> dataList = new ArrayList<String>();
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            int fileCount = 0;
            try{
                fileCount = multiRequest.getFileMap().size();
            }catch (Exception e) {
                fileCount = 0;
                return DtoUtil.returnFail("文件大小超限","100009");
            }
            if(fileCount > 0 && fileCount <= 4 ){
                String token = request.getHeader("token");
                String info=stringRedisTemplate.opsForValue().get(token);
                GdUser user = JSONObject.parseObject(info,GdUser.class);
                if(null != user){
                    //取得request中的所有文件名
                    Iterator<String> iter = multiRequest.getFileNames();
                    while(iter.hasNext()){
                        try{
                            //取得上传文件
                            MultipartFile file = multiRequest.getFile(iter.next());
                            if(file != null){
                                //取得当前上传文件的文件名称
                                String myFileName = file.getOriginalFilename();
                                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                                if(myFileName.trim() !=""
                                        &&
                                        (
                                                myFileName.toLowerCase().contains(".jpg")
                                                        || myFileName.toLowerCase().contains(".jpeg")
                                                        || myFileName.toLowerCase().contains(".png")
                                        ) ){
                                    //重命名上传后的文件名
                                    //命名规则：用户id+当前时间+随机数
                                    String suffixString = myFileName.substring(file.getOriginalFilename().indexOf("."));
                                    String fileName = user.getGd()+ "-" + System.currentTimeMillis() + "-" + ((int)(Math.random()*10000000)) + suffixString;
                                    //定义上传路径
                                    String path = "C:\\Users\\LENOVO\\AppData\\Local\\Temp\\tomcat.1367888122372158707.8150\\work\\Tomcat\\localhost\\ROOT\\"+fileName;
                                    File localFile = new File(path);
                                    file.transferTo(localFile);
                                    dto=DtoUtil.returnSuccess("文件上传成功",path);
                                    AskQusetionVo askQusetionVo =new AskQusetionVo();
                                    askQusetionVo.setUserid(user.getGd());
                                    askQusetionVo.setImageUrl(localFile.toString());
                                    commentService.saveQuestion(askQusetionVo);
                                }
                            }
                        }catch (Exception e) {
                            continue;
                        }
                    }
                }else{
                    dto=DtoUtil.returnFail("文件上传失败","100006");
                }
            }else{
                dto=DtoUtil.returnFail("上传的文件数不正确，必须是大于1小于等于4","100007");
            }
        }
        return  dto;
    }

    /**
     * 提问问题
     * @param askQusetionVo
     * @param request
     * @return
     */
    @RequestMapping(value = "/addQuestion",method= RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<Object> addQuestion(AskQusetionVo askQusetionVo, HttpServletRequest request) {

        String token = request.getHeader("token");
        String info=stringRedisTemplate.opsForValue().get(token);
        GdUser user = JSONObject.parseObject(info,GdUser.class);
        askQusetionVo.setUserid(user.getGd());
        //判断token
        if (user == null ) {
            return DtoUtil.returnFail("token失效，请重新登陆!", "10003");
        }
        if (askQusetionVo == null) {
            return DtoUtil.returnFail("参数错误！", "10005");
        }
        try
        {
           commentService.saveQuestion(askQusetionVo);
        }
        catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("提问问题失败！", "10007");

        }
        return DtoUtil.returnSuccess("提问问题成功！");
    }
}
